﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.Net.InformationPlatform.Entity;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.Net.InformationPlatform.Service.Product.Dto;
using Admin.Net.InformationPlatform.Service.Product.Dto.View;
using Admin.Net.InformationPlatform.Entity.Order;
using Furion.FriendlyException;
using Admin.Net.InformationPlatform.Entity.Product;
using Admin.Net.InformationPlatform.Service.Order.Dto;
using Microsoft.AspNetCore.Http.Features;
using AngleSharp.Css;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinMessageCustomSendRequest.Types;
using System.Drawing;
using Admin.NET.Core;
using Furion.Localization;
using AngleSharp.Io.Dom;
using System.Text.RegularExpressions;
using NewLife.Serialization;
using Admin.Net.InformationPlatform.Service.Product.Dto.T100;
using Dm;
using Newtonsoft.Json;

namespace Admin.Net.InformationPlatform.Service.Product;

[ApiDescriptionSettings(groups: "PlaceOrder", Name = "在线下单", Tag = "订单信息处理", Order = 200)]
public class OrderProductService : IDynamicApiController, ITransient
{
    /// <summary>
    /// 单例数据链接
    /// </summary>
    ISqlSugarClient db;
    /// <summary>
    /// T100数据库
    /// </summary>
    private SqlSugarProvider _T100Db;
    private SqlSugarProvider _SjDb;
    private SqlSugarProvider _plm;
    private SqlSugarProvider _Dilon;
    private SqlSugarProvider _T100TestView;


    /// <summary>
    /// 用户信息
    /// </summary>
    TokenUser _User;
    /// <summary>
    /// 报备客户管理模块
    /// </summary>
    /// <param name="db"></param>
    public OrderProductService(ISqlSugarClient db)
    {
        this.db = db;
        this._T100Db = this.db.AsTenant().GetConnection(T100Const.ConfigId);
        this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
        this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
        this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
        this._T100TestView = this.db.AsTenant().GetConnection(T100TestView.ConfigId);
        // 获取 `Jwt` 存储的信息 企业编号与据点信息
        _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

    }

    /// <summary>
    /// 根据生久料号查询
    /// </summary>
    /// <param name="input">生久料号</param>
    /// <returns></returns>
    [HttpPost("/Order/OrderMessageOutput")]
    public OrderMessageOutput GetOrderMessage(OrderMessageInput input) {

        //缺少理由码和结案码

        Dictionary<string, DHAXMM200_customs005> valuePairs = new Dictionary<string, DHAXMM200_customs005>();

        //交易伙伴关系 收款方和付款方
        List<DHAXMT200_VIEW_PMAC003> PMAC003List = _T100TestView.Ado.SqlQuery<DHAXMT200_VIEW_PMAC003>($@"select * from DHAXMT200_VIEW_PMAC003 where dhpmac001='{input.custNo}' and dhpmac004 in('1','2')").ToList();

        if (PMAC003List.Count==0) {
            throw Oops.Oh("未查到客户的交易伙伴关系！");
        }
        if (PMAC003List.Count>0) {
            foreach (var item in PMAC003List)
            {
                if (item.DHPMAC004.Equals("1")) {
                    List<DHAXMM200_customs005> list = _T100TestView.Ado.SqlQuery<DHAXMM200_customs005>($@"select * from DHAXMM200_customs005 where pmaa001='{item.DHPMAC001}'").ToList();
                    valuePairs.Add("1", list[0]);
                }
                else if (item.DHPMAC004.Equals("2"))
                {
                    List<DHAXMM200_customs005> list = _T100TestView.Ado.SqlQuery<DHAXMM200_customs005>($@"select * from DHAXMM200_customs005 where pmaa001='{item.DHPMAC001}'").ToList();
                    valuePairs.Add("2", list[0]);
                }


            }

        }

        //惯用取价方式
        //客户惯用税种信息
        List<Cxmm200View> viewList = _T100TestView.Ado.SqlQuery<Cxmm200View>($@"select * from cxmm200_view where cxmm200_view001='{input.custNo}'").ToList();

        //料号信息
       List<DHIMAAL_VIEW> dhList = _T100TestView.Ado.SqlQuery<DHIMAAL_VIEW>($@"select * from DHIMAAL_VIEW where dhimaal001='{input.SjMid}'").ToList();

        List<CXMT420_VIEW> cs = _T100TestView.Queryable<CXMT420_VIEW>()
         .Where(it=>it.CXM410_VIEW008 == input.custNo)
         .Where(it => it.CXM410_VIEW010 == input.SjMid)
         .Where(it =>SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(it.CXM410_VIEW002), "yyyy-mm-dd"), "yyyy-mm-dd") == DateTime.Now.Date)
         .OrderByDescending(it => it.CXM410_VIEW018)
         .ToList();


        if (cs.Count==0) {
            throw Oops.Oh("该料号未查到报备信息!");
        }

        OrderMessageOutput messageOutput = new OrderMessageOutput();

        messageOutput.SjProdNo = cs[0].CXM410_VIEW010;
        messageOutput.ProdName = cs[0].CXM410_VIEW011;
        messageOutput.SjProdSpec = cs[0].CXM410_VIEW012;
        messageOutput.Unit = cs[0].CXM410_VIEW013;
        messageOutput.UnitName = cs[0].CXM410_VIEW014;

        messageOutput.SignDate = Convert.ToDateTime(cs[0].CXM410_VIEW002).AddDays(Convert.ToInt32(dhList[0].DHIMAAL010)).ToString("yyyy-MM-dd"); //预计交货日期 
        messageOutput.TaxType = viewList[0].CXMM200_VIEW053;
        messageOutput.Introduce = viewList[0].CXMM200_VIEW054;
        messageOutput.TaxLv = viewList[0].CXMM200_VIEW056;

        //税率转小数
        double lv = (double)messageOutput.TaxLv/ 100;

        if (viewList[0].CXMM200_VIEW042.Equals("X08")) {
            messageOutput.UnitPrice = cs[0].CXM410_VIEW016;
        }
        else {
            messageOutput.UnitPrice = cs[0].CXM410_VIEW015;
        }
        
        messageOutput.BedorePrice = messageOutput.UnitPrice * (1- lv);//税前金额 
        messageOutput.IntroStatus = messageOutput.UnitPrice;//含税金额
        messageOutput.TaxPrice = messageOutput.UnitPrice * lv;//税额 
        messageOutput.Stock = dhList[0].DHIMAAL011; //库存
        messageOutput.PurchasePrice = messageOutput.UnitPrice;//订购金额
        if (valuePairs.Count>0 && valuePairs["1"]!=null) {
            messageOutput.InchargeArea = valuePairs["1"].pmaaud002;
            messageOutput.InchargeAreaName = valuePairs["1"].ooefl003;
        }
        if (valuePairs.Count > 0 && valuePairs["2"] != null) {
            messageOutput.DeliveryArea = valuePairs["2"].pmaaud002;//出货地点
            messageOutput.DeliveryAreaName = valuePairs["2"].ooefl003;//出货地点名称
        }

        messageOutput.Emgency = viewList[0].CXMM200_VIEW046;//客户经营类型

        return messageOutput;
    }

    /// <summary>
    /// 添加订单信息
    /// </summary>
    /// <returns></returns>
    [HttpPost("/Order/AddOrderMessage")]
    public async Task<string> AddOrderMessage(OrderCustomerInput input) {

        #region 信息验证
        if (input == null)
        {
            throw Oops.Oh("请传入客户信息！");
        }
        if (string.IsNullOrEmpty(input.OrderTypeName))
        {
            throw Oops.Oh("订单类别不能为空！");
        }
        if (string.IsNullOrEmpty(input.UserDepartmentName) || string.IsNullOrEmpty(input.CustName) || string.IsNullOrEmpty(input.CustNo))
        {
            throw Oops.Oh("业务员部门和业务员信息不能为空!");
        }
        if (string.IsNullOrEmpty(input.TaxTypeName))
        {
            throw Oops.Oh("收款条件不能为空!");
        }
        if (input.AnnexUrlList.Count == 0)
        {
            throw Oops.Oh("项目附件不能为空!");
        }
        if (string.IsNullOrEmpty(input.UserName) || string.IsNullOrEmpty(input.UserNo))
        {
            throw Oops.Oh("客户简称不能为空!");
        }
        if (input.OrderDate == null)
        {
            throw Oops.Oh("订单日期不能为空!");
        }
        if (DateTime.Compare(Convert.ToDateTime(input.OrderDate), DateTime.Now) > 0)
        {
            throw Oops.Oh("订单日期不能大于当前时间!");
        }
        if (input.OrderMessageInputList.Count==0) {
            throw Oops.Oh("请输入产品列表信息!");
        }

        foreach (var orderMessage in input.OrderMessageInputList)
        {
            if (string.IsNullOrEmpty(orderMessage.SjMid)) {
                throw Oops.Oh("请输入生久料号!");
            }
            if (string.IsNullOrEmpty(orderMessage.Unit)) {
                throw Oops.Oh("单位不能为空!");
            }
            if (orderMessage.PurchaseQuantity==0)
            {
                throw Oops.Oh("订购量不能为空!");
            }
            if (DateTime.Compare(Convert.ToDateTime(orderMessage.SignDate), DateTime.Now.Date)< 0) {
                throw Oops.Oh("预计交货日期不能大于当前小于当前日期!");
            }

            if (string.IsNullOrEmpty(orderMessage.ProdName) || string.IsNullOrEmpty(orderMessage.SjProdSpec) ||
                string.IsNullOrEmpty(orderMessage.UnitName) ) {

                throw Oops.Oh("请填写完整产品信息!");
            }


        }
        #endregion

        List<Cxmm200View> viewList = _T100TestView.Ado.SqlQuery<Cxmm200View>($@"select * from cxmm200_view where cxmm200_view001='{input.UserNo}'").ToList();

        //交易伙伴关系 收款方和付款方
        List<DHAXMT200_VIEW_PMAC003> PMAC003List = _T100TestView.Ado.SqlQuery<DHAXMT200_VIEW_PMAC003>($@"select * from DHAXMT200_VIEW_PMAC003 where dhpmac001='{input.UserNo}' and dhpmac004 in('1','2')").ToList();


        List<DHAXMM202_CUSTOMS001> viewList1 = _T100TestView.Ado.SqlQuery<DHAXMM202_CUSTOMS001>($@" select * from DHAXMM202_CUSTOMS001 where pmab001='{input.UserNo}'").ToList();


        List<DHAXMM202_CUSTOMS008> viewList2 = _T100TestView.Ado.SqlQuery<DHAXMM202_CUSTOMS008>($@"select * from DHAXMM202_CUSTOMS008 where pmab001 ='{input.UserNo}'").ToList();


        Dictionary<string, DHAXMM200_customs005> valuePairs = new Dictionary<string, DHAXMM200_customs005>();

        if (PMAC003List.Count > 0)
        {
            foreach (var item in PMAC003List)
            {
                if (item.DHPMAC004.Equals("1"))
                {
                    List<DHAXMM200_customs005> list = _T100TestView.Ado.SqlQuery<DHAXMM200_customs005>($@"select * from DHAXMM200_customs005 where pmaa001='{item.DHPMAC001}'").ToList();
                    valuePairs.Add("1", list[0]);
                }
                else if (item.DHPMAC004.Equals("2"))
                {
                    List<DHAXMM200_customs005> list = _T100TestView.Ado.SqlQuery<DHAXMM200_customs005>($@"select * from DHAXMM200_customs005 where pmaa001='{item.DHPMAC001}'").ToList();
                    valuePairs.Add("2", list[0]);
                }


            }

        }

        AXMT500 axmt = new AXMT500();
        axmt.key = "f5458f5c0f9022db743a7c0710145903";
        axmt.type = "sync";
        axmt.host = new HostClass()
        {
            prod = "ds",
            lang = "zh_CN",
            acct = "tiptop",
            timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds().ToString(),

        };
        axmt.service = new ServiceClass()
        {
            name = "ds.create.axmt500",
            id = "toptst"
        };
        axmt.datakey = new DatakeyClass()
        {
            EntId = "8",
            CompanyId = "SJGS"
        };

        axmt.payload = new Payload()
        {

            std_data = new StdData
            {
                parameter = new Parameter()
                {
                    xmdadocno = "xm61",
                    xmda004 = input.UserNo,
                    xmda039 = "1",
                    xmdadocdt = DateTime.Now.Date.ToString("yyyy/MM/dd"),
                    xmda002 = input.CustNo,
                    xmda003 = input.UserDepartment,
                    xmda009 = input.TaxTypeName,
                    xmda010 = viewList1[0].Pmab103,
                    xmda011 = viewList[0].CXMM200_VIEW053,
                    xmda035 = viewList2[0].Pmab106,
                    xmda015 = input.CoinType,
                    xmda017 = viewList[0].CXMM200_VIEW042,
                    xmda021 = !string.IsNullOrEmpty(valuePairs["1"].pmaa001) ? valuePairs["1"].pmaa001 : "",
                    xmda022 = !string.IsNullOrEmpty(valuePairs["2"].pmaa001) ? valuePairs["1"].pmaa001 : "",
                    xmdb_type = "1",
                    xmdaud010 = input.CustNumber,
                    xmdaud009 = "1",//电商订单来源
                    xmda008 = "",// 客户来源单号
                    xmda033 = input.CustomrOrderId,//客户订购单号
                    xmda071 = input.OrderRemark,
                    xmdaownid = input.UserNo

                }

            }
        };


        StringBuilder url = new StringBuilder();
        if (input.AnnexUrlList.Count > 0)
        {
            for (int i = 0; i < input.AnnexUrlList.Count; i++)
            {
                url.Append(input.AnnexUrlList[i]);
                if ((i + 1) < input.AnnexUrlList.Count)
                {
                    url.Append(";");
                }
            }
        }

        OrderCustomer customer = new OrderCustomer()
        {
            ORDERID = input.CustNumber,
            ORDERDATE = DateTime.Now.Date,         //订单日期
            BUSINESSPERSON = input.CustNo,
            PERSONNAME = input.CustName,
            BUSINESSUNIT = input.UserDepartmentName,
            CUSTOMERID = input.UserNo,
            CUSTOMERNAME = input.UserName,
            CUSTOMERORDERID = input.CustomrOrderId,
            ORDERPROPERTIES = input.OrderDataName,
            ORDERTYPE = input.OrderTypeName,
            AUDITSTATUS = 0,         //审核状态
            COLLECTIONCONDITION = input.TaxTypeName,
            CURRENCY = input.CoinTypeName,
            ACQUISITIONWAY = input.GetPriceTypeName,
            ORDERREMARK = input.OrderRemark,
            ANNEX = url.ToString(),
            CERATETIME = DateTime.Now         //创建日期

        };

        List<OrderProduct> orderProductList = new List<OrderProduct>();


       

        foreach (InsertOrderMessageInput insert in input.OrderMessageInputList)
        {
            int i = 1;
            OrderProduct product = new OrderProduct()
            {

                ORDERID = input.CustNumber,
                CUSTOMERID = input.UserNo,
                CUSTOMERNAME = input.UserName,
                CUSTOMERMID = insert.CustomerMid,
                CUSTOMERMNAME = insert.CustomerMname,
                MATERIALSPECS = insert.MaterialSpecs,
                SJMID=insert.SjMid,
                BOMFEATURE = insert.BomFeature,
                MNAME = insert.ProdName,
                SPECS =insert.SjProdSpec,
                UNITLENGTH = insert.Unit,
                UNITNAME = insert.UnitName,
                COUPLERLENGTH = insert.CouplerLength,
                PURCHASEQUANTITY = insert.PurchaseQuantity,
                CUSTOMERINFORMATION = insert.CustomerInformation,
                PRESETDATE = insert.SignDate,
                ROWSTATUS = insert.RowStatus,
                TAXMESSAGE = insert.TaxType,
                ORDERDESCRIPTION = insert.Introduce,
                TAXRATES = insert.TaxLv,
                PRETAXAMOUNT = insert.BedorePrice,
                HAVETAXAMOUNT =insert.IntroStatus,
                TAXCOUNT = insert.TaxPrice,
                INVENTORY = insert.Stock,
                ORDERAMOUNT = insert.PurchasePrice,
                ORDERREMARK = insert.OrderRemark,
                LONGREMARK =insert.LongRemark,
                ORDERDATE = DateTime.Now.Date,
                ORDERSTATUS=0,
                REASONCODE = insert.ReasonCode,
                REASONCODEEXPLAIN = insert.ReasonCodeExplain,
                FINISHECODE = insert.FinisheCode,
                FINISHECODEEXPLAIN = insert.FinisheCodeExplain,
                INCHARGEAREA=insert.InchargeArea,
                INCHARGEAREANAME=insert.InchargeArea,
                DELIVERYAREA=insert.DeliveryArea,
                DELIVERYAREANAME =insert.DeliveryAreaName,
                URGENCY = insert.Urgency,
            };

            if (insert.IsPartialDelivery) {
                product.ISPARTIALDELIVERY = 0;
            }else if (insert.IsPartialDelivery) {
                product.ISPARTIALDELIVERY = 1;
            }

            orderProductList.Add(product);

            axmt.payload.std_data.parameter.detail_xmdc = new List<DetailXmdc>() {
            new DetailXmdc() {
                xmdcseq = i,
                xmdc001 = product.SJMID,
                xmdc007 = product.PURCHASEQUANTITY,
                xmdc015 = product.ORDERAMOUNT,
                xmdcud001 = product.COUPLERLENGTH,
                xmdc050 = product.ORDERREMARK,
                ooff013 = product.LONGREMARK

            }};
            i++;

/*            axmt.Payload.Std_data.Parameter.detail_xmdc.Add(new DetailXmdc() {
                xmdcseq = i,
                xmdc001 = product.SJMID,
                xmdc007 = product.PURCHASEQUANTITY,
                xmdc015 = product.ORDERAMOUNT,
                xmdcud001 = product.COUPLERLENGTH,
                xmdc050 = product.ORDERREMARK,
                ooff013 = product.LONGREMARK

            });*/
           
        }






        AXMT500Out xMT500Out = await this.AddT100_AXMT500(axmt);

        if (xMT500Out == null || string.IsNullOrEmpty(xMT500Out.payload.parameter.docno)) {
            throw Oops.Oh($"调用T100任务失败！");
        }

        foreach (var item in orderProductList)
        {
            item.T100ID = xMT500Out.payload.parameter.docno;
        }


        #region 插入事务
        try
        {
            //开启事务
            _SjDb.Ado.BeginTran();
            int cnt = await _SjDb.Insertable<OrderCustomer>(customer).ExecuteCommandAsync();

            int cnt2 = await _SjDb.Insertable(orderProductList).ExecuteCommandAsync();

            if (cnt == 0 || cnt2==0)
            {
                throw Oops.Oh($"新建任务失败！");
            }
            //提交事务
            _SjDb.Ado.CommitTran();
            return "插入成功";
        }
        catch (Exception e)
        {
            //回滚事务
            _SjDb.Ado.RollbackTran();
            throw Oops.Oh($"异常：{e.Message}");
        }
        #endregion



    }

    /// <summary>
    /// 订单信息查询
    /// </summary>
    /// <param name="input"></param>
    [HttpPost("/Order/SelectOrderMessage")]
    public async Task<SqlSugarPagedList<OrderCustomerBySelectOutput>> SelectOrderMessage(OrderCustomerBySelectInput input)
    {

        // 缺权限管控

        var orderCustomerList = await _SjDb.Queryable<OrderCustomer>()
        .WhereIF(!string.IsNullOrEmpty(input.OrderId), (l) => (l.ORDERID == input.OrderId))//订单编号
        .WhereIF(!string.IsNullOrEmpty(input.UserName), (l) => (l.CUSTOMERNAME == input.UserName))//客户简称
        .WhereIF(input.StartTime != null, b => (SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(b.ORDERDATE), "yyyy-mm-dd"), "yyyy-mm-dd") >= input.StartTime))//下单开始日期
        .WhereIF(input.EndTime != null, b => (SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(b.ORDERDATE), "yyyy-mm-dd"), "yyyy-mm-dd") <= input.EndTime))//下单结束日期
       .OrderBy(l => l.ORDERID, OrderByType.Desc) //订单编号
       .Select(a => new OrderCustomerBySelectOutput
       {
           OrderId = a.ORDERID,
           UserName = a.CUSTOMERNAME,
           CustName = a.PERSONNAME,
           UserDepartmentName = a.BUSINESSUNIT,
           CustomrOrderId = a.CUSTOMERORDERID,
           OrderDataName = a.ORDERPROPERTIES,
           TaxTypeName = a.COLLECTIONCONDITION,
           CoinType = a.CURRENCY,
           GetPriceType = a.ACQUISITIONWAY,
           OrderRemark = a.ORDERREMARK,
           LongRemark = a.ANNEX


       }).ToPagedListAsync(input.Page, input.PageSize);




        List<OrderCustomerBySelectOutput> list1 = (List<OrderCustomerBySelectOutput>)orderCustomerList.Items;

        for (int i = 0; i < list1.Count; i++)
        {
            if (!string.IsNullOrEmpty(list1[i].LongRemark)) {
                list1[i].FileList = list1[i].LongRemark.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            }
        }

        var output =  _SjDb.Queryable<OrderProduct>()
          .WhereIF(!string.IsNullOrEmpty(input.OrderId), (l) => (l.ORDERID == input.OrderId))//订单编号
          .WhereIF(!string.IsNullOrEmpty(input.UserName), (l) => (l.CUSTOMERNAME == input.UserName))//客户简称
         .WhereIF(!string.IsNullOrEmpty(input.SjMid), (l) => (l.SJMID == input.SjMid))//产品料号
         .WhereIF(input.OrderStatus!=null, (l) => (l.ORDERSTATUS == input.OrderStatus))//产品状态
         .WhereIF(input.StartTime != null, b => (SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(b.ORDERDATE), "yyyy-mm-dd"), "yyyy-mm-dd") >= input.StartTime))//下单开始日期
         .WhereIF(input.EndTime != null, b => (SqlFunc.Oracle_ToDate(SqlFunc.Oracle_ToChar(Convert.ToDateTime(b.ORDERDATE), "yyyy-mm-dd"), "yyyy-mm-dd") <= input.EndTime))//下单结束日期

       .OrderBy(l => l.ORDERID, OrderByType.Desc) //订单编号
       .OrderBy(l => l.ORDERDATE, OrderByType.Desc) //下单日期排序
       .Select(a => new OrderCustomerBySelectOutput
       {
           OrderId = a.ORDERID,
           UserName = a.CUSTOMERNAME,
           SjMid = a.CUSTOMERMID,//产品料号
           CheckStatus = a.ORDERSTATUS.ToString(),//审核状态
           CustProNum = a.CUSTOMERMID,
           CustProName = a.CUSTOMERMNAME,
           SjProdSpec = a.SPECS,//规格
           OrderStatus = a.ORDERSTATUS.ToString(),//订单状态
           Unit = a.UNITLENGTH,//单位
           UnitName = a.UNITNAME,//单位名称
           TaxType = a.TAXMESSAGE,//税种
           Introduce = a.ORDERDESCRIPTION,
           TaxLv = a.TAXRATES,
           UnitPrice = a.HAVETAXAMOUNT,
           BedorePrice = a.PRETAXAMOUNT,
           IntroStatus = a.HAVETAXAMOUNT,
           TaxPrice = a.TAXCOUNT,
           PurchaseQuantity = a.PURCHASEQUANTITY,
           PurchasePrice = a.PURCHASEQUANTITY * a.HAVETAXAMOUNT,
           Stock = a.INVENTORY,
           OrderDate = a.ORDERDATE,
           SignDate = a.PRESETDATE,
           MaterialSpecs = a.MATERIALSPECS,
           BomFeature = a.BOMFEATURE,
           CouplerLength = a.COUPLERLENGTH,
           RowStatus = a.ROWSTATUS,
           Urgency = a.URGENCY,
           IsPartialDelivery = a.ISPARTIALDELIVERY == 0 ? true : false,
           DeliveryArea = a.DELIVERYAREA,
           DeliveryAreaName = a.DELIVERYAREANAME,
           InchargeArea = a.INCHARGEAREA,
           InchargeAreaName = a.INCHARGEAREANAME,
           ReasonCode = a.REASONCODE,
           ReasonCodeExplain = a.REASONCODEEXPLAIN,
           FinisheCode = a.FINISHECODE,
           FinisheCodeExplain = a.FINISHECODEEXPLAIN,
           LongRemark = a.LONGREMARK,
           T100ID = a.T100ID,

       }).ToList();



        if (list1.Count != 0 && output.Count != 0)
        {
            var result = from o in output
                         join c in list1 on o.OrderId equals c.OrderId into OrderId
                         from c in OrderId.DefaultIfEmpty()
                         select new OrderCustomerBySelectOutput
                         {
                             OrderId = c.OrderId,
                             UserName = c.UserName,
                             CustName = c.CustName,
                             UserDepartmentName = c.UserDepartmentName,
                             CustomrOrderId = c.CustomrOrderId,
                             OrderDataName = c.OrderDataName,
                             TaxTypeName = c.TaxTypeName,
                             CoinType = c.CoinType,
                             GetPriceType = c.GetPriceType,
                             OrderRemark = c.OrderRemark,
                             FileList = c.FileList,
                             SjMid = o.SjMid,//产品料号
                             CheckStatus = o.CheckStatus.Equals("0") ? "已审核" : "未审核",//审核状态
                             CustProNum = o.CustProNum,
                             CustProName = o.CustProName,
                             SjProdSpec = o.SjProdSpec,//规格
                             OrderStatus = o.OrderStatus.ToString(),//订单状态
                             Unit = o.Unit,//单位
                             UnitName = o.UnitName,//单位名称
                             TaxType = o.TaxType,//税种
                             Introduce = o.Introduce,
                             TaxLv = o.TaxLv,
                             UnitPrice = o.UnitPrice,
                             BedorePrice = o.BedorePrice,
                             IntroStatus = o.IntroStatus,
                             TaxPrice = o.TaxPrice,
                             PurchaseQuantity = o.PurchaseQuantity,
                             PurchasePrice = o.PurchasePrice,
                             Stock = o.Stock,
                             OrderDate = o.OrderDate,
                             SignDate = o.SignDate,
                             MaterialSpecs = o.MaterialSpecs,
                             BomFeature = o.BomFeature,
                             CouplerLength = o.CouplerLength,
                             RowStatus = o.RowStatus,
                             Urgency = o.Urgency,
                             IsPartialDelivery = o.IsPartialDelivery,
                             DeliveryArea = o.DeliveryArea,
                             DeliveryAreaName = o.DeliveryAreaName,
                             InchargeArea = o.InchargeArea,
                             InchargeAreaName = o.InchargeAreaName,
                             ReasonCode = o.ReasonCode,
                             ReasonCodeExplain = o.ReasonCodeExplain,
                             FinisheCode = o.FinisheCode,
                             FinisheCodeExplain = o.FinisheCodeExplain,
                             LongRemark = o.LongRemark,
                             T100ID = o.T100ID,

                         };

            // 审核状态 缺少

            orderCustomerList.Items = result;


            return orderCustomerList;

        }


        return null;
    }

    /// <summary>
    /// 计算订单价格信息
    /// </summary>
    /// <param name="order"></param>
    /// <returns></returns>
    [HttpPost("/Order/GetPriceMessage")]
    public async Task<Price> GetPriceMessage([FromBody]List<PriceInput> order) {

        if (order!=null) {

            int ProductCount = 0;
            double TotalAmount = 0;
            foreach (var item in order)
            {
                ProductCount += item.PurchaseQuantity;
                TotalAmount += item.PurchasePrice;

            }

            Price price = new Price() { 
            ProductCount = order.Count,
            TotalAmount = TotalAmount,
            TotalProduct = ProductCount

            };

            return price;
        }

        return null;
    }

    /// <summary>
    /// 调用t100接口
    /// </summary>
    /// <returns></returns>
    private async Task<AXMT500Out> AddT100_AXMT500(AXMT500 axmt500) {

       string jsonString =  JsonConvert.SerializeObject(axmt500);

        string a = await PostAsyncJson("http://192.168.1.21/wtoptst/ws/r/awsp920", jsonString);

        if (!string.IsNullOrEmpty(a)) {
            AXMT500Out xMT500 = JsonConvert.DeserializeObject<AXMT500Out>(a);

            return xMT500;
        }
        return null;
       
    }



    private static async Task<string> PostAsyncJson(string url, string json)
    {
        string responseBody = string.Empty;
        using (HttpClient client = new HttpClient())
        {
            HttpContent content = new StringContent(json);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            //request.Headers.Authorization = new AuthenticationHeaderValue("Authorization", token);
            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    responseBody = await response.Content.ReadAsStringAsync();
                }
            }
            catch (Exception)
            {

                throw;
            }


        }
        Console.WriteLine(responseBody);
        return responseBody;
    }

}
